import { componentMap, constantRoutes } from '@/router'
import { getMenu } from '@/api/user'
import { deepClone } from '@/utils';
/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes (data) {
    let oData = deepClone(data)
    let res = [];
    let tmpMap = {};
    oData.forEach((route, index) => {
        let router = JSON.parse(route.urlJson)
        router.component = componentMap[router.component]?.component
        oData[index] = {
            id: route.id,
            pid: route.pid,
            ...router
        }
        tmpMap[route["id"]] = oData[index]
    });
    oData.forEach(router => {
        let key = tmpMap[router["pid"]];
        if (key) {
            if (!key["children"]) {
                key["children"] = [];
                key["children"].push(router);
            } else {
                key["children"].push(router);
            }
        } else if (router.pid == -1) {
            res.push(router);
        }
    })
    return res;
}

const state = {
    routes: [],
    addRoutes: [],
    baseRoutesMap: [],
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        state.addRoutes = routes
        state.routes = constantRoutes.concat(routes)
    },
    SET_BASE_ROUTES_MAP: (state, routes) => {
        state.baseRoutesMap = routes
    }
}

const actions = {
    generateRoutes ({ commit, state }) {
        return new Promise((resolve, reject) => {
            getMenu().then(response => {
                let { data } = response
                data = data || []
                let baseMap = deepClone(data).map(item => {
                    item.urlJson = JSON.parse(item.urlJson)
                    return item
                })
                commit('SET_BASE_ROUTES_MAP', baseMap)
                let accessedRoutes = filterAsyncRoutes(data)
                commit('SET_ROUTES', accessedRoutes)
                //路由表末尾添加全匹配 404
                accessedRoutes.push({ path: '*', redirect: '/404', hidden: true })
                resolve(accessedRoutes)
            }).catch(error => {
                console.log(error);
                reject(error)
            })
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}
